package com.turing.post.salesmanage.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.salesmanage.util.BranchDaySett_Obj;
import com.turing.post.salesmanage.util.DepositOrderPaidDetail;
import com.turing.post.salesmanage.util.DepositOrderPaidDetailDao;
import com.turing.post.util.Config;
import com.turing.post.util.GeneralDao;
import com.turing.post.util.PCPSApplicationException;

/**
 * 充值单付款信息（DepositOrderPaidDetail）
 * 
 * @author zxp
 * @Jan 17, 2013
 */
@Stateless(mappedName = "salesmanage.impl.DepositOrderPaidDetailDaoImpl")
@Remote
@Local
public class DepositOrderPaidDetailDaoImpl implements DepositOrderPaidDetailDao {

	@PersistenceContext
	protected EntityManager _em;

	@Override
	public DepositOrderPaidDetail getDepositOrderPaidDetailByPaidId(
			BigInteger depositOrderPaidId) {
		return _em.find(DepositOrderPaidDetail.class, depositOrderPaidId);
	}

	@Override
	public DepositOrderPaidDetail getDepositOrderPaidDetailForUpdate(
			BigInteger depositOrderPaidId) {
		String sql = "select * from DepositOrderPaidDetail t where t.DepositOrderPaidId="
				+ depositOrderPaidId + " for update";
		Query query = _em.createNativeQuery(sql, DepositOrderPaidDetail.class);
		return (DepositOrderPaidDetail) query.getSingleResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<DepositOrderPaidDetail> getDepositOrderPaidDetailListByDepositOrderId(
			BigInteger depositOrderId) {
		String sql = "select * from DepositOrderPaidDetail t where t.DepositOrderId="
				+ depositOrderId + " order by tranTime";
		Query query = _em.createNativeQuery(sql, DepositOrderPaidDetail.class);
		return query.getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<DepositOrderPaidDetail> getDepositOrderPaidDetailListByCondition(
			BigInteger depositOrderId, String paidType,
			BigInteger startPaidAmount, BigInteger endPaidAmount,
			String paidClass, Integer page) {
		int maxResult = Config.PAGE_SIZE;
		int startPosition = maxResult * page;
		// 平台管理员无法查询
		String sql = "select t.* from DepositOrderPaidDetail t where DepositOrderId = ?1 and (?2 is null or PaidType=?2) and "
				+ "(?3 is null or PaidAmount>=to_number(?3)) and (?4 is null or PaidAmount<=to_number(?4)) and (?5 is null or paidClass=?5) order by tranTime";
		Query query = null;
		if (page == -1){
			query = _em.createNativeQuery(sql, DepositOrderPaidDetail.class);
		}else{
			query = _em.createNativeQuery(sql, DepositOrderPaidDetail.class)
					.setFirstResult(startPosition).setMaxResults(maxResult);
		}
		query.setParameter(1, depositOrderId);
		query.setParameter(2, paidType);
		query.setParameter(3, startPaidAmount);
		query.setParameter(4, endPaidAmount);
		query.setParameter(5, paidClass);
		List<DepositOrderPaidDetail> orderList = query.getResultList();
		List<DepositOrderPaidDetail> returnList = new ArrayList<DepositOrderPaidDetail>();
		for (DepositOrderPaidDetail dopd : orderList) {
			if (dopd.getCancelDepositOrderPaidId() == null) {
				dopd.setCancelBtn("PaidOffCanceled");
				returnList.add(dopd);
			} else {
				dopd.setCancelBtn("");
				returnList.add(dopd);
			}
		}
		return returnList;
	}

	@Override
	public BigInteger getDepositOrderPaidDetailTotalByCondition(
			BigInteger depositOrderId, String paidType,
			BigInteger startPaidAmount, BigInteger endPaidAmount,
			String paidClass) {
		String sql = "select nvl(count(*),0) from DepositOrderPaidDetail t where DepositOrderId = ?1 and (?2 is null or PaidType=?2) and "
				+ "(?3 is null or PaidAmount>=to_number(?3)) and (?4 is null or PaidAmount<=to_number(?4)) and (?5 is null or paidClass=?5)";
		Query query = _em.createNativeQuery(sql);
		query.setParameter(1, depositOrderId);
		query.setParameter(2, paidType);
		query.setParameter(3, startPaidAmount);
		query.setParameter(4, endPaidAmount);
		query.setParameter(5, paidClass);
		return new BigInteger(query.getSingleResult().toString());
	}

	@Override
	public void insertDepositOrderPaidDetail(DepositOrderPaidDetail dopd)
			throws PCPSApplicationException {
		GeneralDao.insert(_em, dopd);
	}

	@Override
	public void updateDepositOrderPaidDetail(DepositOrderPaidDetail dopd)
			throws PCPSApplicationException {
		GeneralDao.update(_em, dopd);
	}

	private BigInteger getValue(Object[] o, int idx) {
		if (o == null || idx < 0 || idx > o.length || o[idx] == null)
			return BigInteger.ZERO;

		return new BigInteger(o[idx].toString());
	}

	@SuppressWarnings("unchecked")
	private BranchDaySett_Obj getBranchDaySettByBranchNoAndTranDate(
			String saleBranchNo, Date tranDate, String sql, String dsql) {
		Query query = _em.createNativeQuery(sql);
		query.setParameter(1, saleBranchNo);
		query.setParameter(2, tranDate);
		List<Object[]> slist = query.getResultList();
		if (slist == null || slist.isEmpty()) {
			slist = new ArrayList<Object[]>();
			slist.add(new Object[] { "0", "0" });
		}

		Object[] sobj = slist.get(0);

		Query dquery = _em.createNativeQuery(dsql);
		dquery.setParameter(1, saleBranchNo);
		dquery.setParameter(2, tranDate);
		List<Object[]> dlist = dquery.getResultList();
		if (dlist == null || dlist.isEmpty()) {
			dlist = new ArrayList<Object[]>();
			dlist.add(new Object[] { "0", "0", "0", "0", "0", "0" });
		}

		Object[] dobj = dlist.get(0);

		BranchDaySett_Obj bds = new BranchDaySett_Obj();
		bds.setSaleBranchNo(saleBranchNo);
		bds.setTranDate(tranDate);
		bds.setTranCount(getValue(sobj, 0));
		bds.setCashAmount(getValue(dobj, 0));
		bds.setChequeAmount(getValue(dobj, 1));
		bds.setTranAmount(getValue(dobj, 2));
		bds.setCashFee(getValue(dobj, 3));
		bds.setChequeFee(getValue(dobj, 4));
		bds.setTranFee(getValue(dobj, 5));
		bds.setCardFee(BigInteger.ZERO);
		bds.setDiscountFee(getValue(sobj, 1));

		return bds;
	}

	/**
	 * 产生指定机构某日充值汇总数据
	 * 
	 * @param saleBranchNo
	 * @param tranDate
	 * @return
	 */
	public List<BranchDaySett_Obj> getBranchDaySettByBranchNoAndTranDate(
			String saleBranchNo, Date tranDate) {
		final String sale_sql = "select count(distinct s.DepositOrderId), sum(s.Fee - s.FactFee) from DepositOrder s where s.SaleBranchNo = ?1 and s.TranDate = ?2 ";
		final String sale_csql = "select count(distinct s.DepositOrderId), sum(s.Fee - s.FactFee) from DepositOrder s where s.SaleBranchNo = ?1 and s.CancelDate = ?2 ";
		final String sum_sql = "nvl(sum( case when p.PaidType = '0' and p.PaidClass = '0' then p.PaidAmount else 0 end),0), " // 现金销售额
				+ "nvl(sum( case when p.PaidType = '1' and p.PaidClass = '0' then p.PaidAmount else 0 end),0), " // 支票销售额
				+ "nvl(sum( case when p.PaidType = '2' and p.PaidClass = '0' then p.PaidAmount else 0 end),0), " // 转账销售额
				+ "nvl(sum( case when p.PaidType = '0' and p.PaidClass = '1' then p.PaidAmount else 0 end),0), " // 现金手续费
				+ "nvl(sum( case when p.PaidType = '1' and p.PaidClass = '1' then p.PaidAmount else 0 end),0), " // 支票手续费
				+ "nvl(sum( case when p.PaidType = '2' and p.PaidClass = '1' then p.PaidAmount else 0 end),0) " // 转账手续费
		;
		final String sql = "select "
				+ sum_sql
				+ "from DepositOrderPaidDetail p "
				+ "where p.TranDate = ?2 and p.PaidAmount > 0 and p.DepositOrderId in ( select s.DepositOrderId from DepositOrder s where s.SaleBranchNo = ?1 and s.TranDate = ?2 )";
		final String csql = "select "
				+ sum_sql
				+ "from DepositOrderPaidDetail p "
				+ "where p.TranDate = ?2 and p.PaidAmount < 0 and p.DepositOrderId in ( select s.DepositOrderId from DepositOrder s where s.SaleBranchNo = ?1 and s.CancelDate = ?2 )";

		BranchDaySett_Obj bds_normal = getBranchDaySettByBranchNoAndTranDate(
				saleBranchNo, tranDate, sale_sql, sql);
		bds_normal.setTranType(BranchDaySett_Obj.TRANTYPE_DEPOSIT);

		BranchDaySett_Obj bds_cancel = getBranchDaySettByBranchNoAndTranDate(
				saleBranchNo, tranDate, sale_csql, csql);
		bds_cancel.setTranType(BranchDaySett_Obj.TRANTYPE_DEPOSIT_CANCEL);

		List<BranchDaySett_Obj> bdslist = new ArrayList<BranchDaySett_Obj>();

		if (!bds_normal.isAllZero())
			bdslist.add(bds_normal);

		if (!bds_cancel.isAllZero())
			bdslist.add(bds_cancel);

		return bdslist;
	}
}